package club.zhcs.captrue.module.auth;

import java.util.List;

import org.nutz.dao.entity.Record;
import org.nutz.ioc.loader.annotation.Inject;
import org.nutz.mvc.annotation.At;
import org.nutz.mvc.annotation.GET;
import org.nutz.mvc.annotation.Ok;
import org.nutz.mvc.annotation.POST;
import org.nutz.mvc.annotation.Param;

import club.zhcs.capture.bean.auth.Role;
import club.zhcs.capture.biz.auth.impl.RoleService;
import club.zhcs.capture.vo.Consts.PermissionGroup;

import com.dgj.nutz.module.base.AbstractBaseModule;
import com.dgj.utils.entries.Result;
import com.dgj.utils.web.pager.Pager;

/**
 * @author 黄敏 create at 2015年9月11日
 */
@At("/role")
public class RoleModule extends AbstractBaseModule {

	@Inject
	private RoleService roleService;

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.dgj.nutz.module.base.AbstractBaseModule#_getNameSpace()
	 */
	@Override
	public String _getNameSpace() {
		return PermissionGroup.USER_ADMIN.getNameSpace();
	}

	@At
	@Ok("vel:role/list.html")
	public Result list(int page) {
		page = _fixPage(page);
		Pager<Role> pager = roleService.findByPage(page);
		pager.setUrl(_base() + "/role/list");
		return Result.success().addData("pager", pager);
	}

	@At
	@GET
	@Ok("vel:role/add.html")
	public Result add() {
		return Result.success();
	}

	@At
	@POST
	public Result add(@Param("..") Role role) {
		if (null != roleService.findByName(role.getName())) {
			return Result.fail("角色" + role.getName() + "已存在");
		}
		role = roleService.addRole(role);
		role.setInstalled(false);
		return role == null ? Result.fail("添加角色失败") : Result.success().addData("role", role);
	}

	@At("/delete/*")
	public Result delete(int id) {
		return roleService.delete(id);
	}

	@At("/info/*")
	@Ok("vel:role/detail.html")
	public Result info(int id, @Param("..") Role role) {
		role = roleService.findById(id);
		return Result.success().addData("role", role);
	}

	@At
	@Ok("vel:role/list.html")
	public Result search(int page, String key) {
		page = _fixPage(page);
		key = _fixSearchKey(key);
		Pager<Role> pager = roleService.searchByKey(page, key);
		pager.setUrl(_base() + "/role/search");
		pager.addParas("key", key);
		return Result.success().addData("pager", pager);
	}

	@At("/edit/*")
	@Ok("vel:role/edit.html")
	public Result edit(int id, @Param("..") Role role) {
		role = roleService.findById(id);
		return Result.success().addData("role", role);
	}

	@At
	@POST
	public Result update(@Param("..") Role role) {
		return roleService.upate(role, new String[] { "description" });
	}

	@At("/setPermission/*")
	@GET
	@Ok("vel:role/set_permission.html")
	public Result setPermission(int id) {
		List<Record> record = roleService.findRolePermissionByUserId(id);
		return Result.success().addData("record", record).addData("roleId", id);
	}

	@At
	@POST
	public Result setPermission(@Param("ids") int[] ids, int roleId) {
		return roleService.setPermission(ids, roleId);
	}
}
